package com.kancy.springcloudconfig.action;

import com.kancy.springcloudconfig.action.model.AlgorithmData;
import com.kancy.springcloudconfig.action.model.RefreshObject;
import com.kancy.springcloudconfig.constants.Constants;
import com.kancy.springcloudconfig.exception.AlertException;
import com.kancy.springcloudconfig.util.CommonUtil;
import com.kancy.springcloudconfig.util.RSAUtil;

/**
 * <p>
 * RsaAlgorithAction
 * </p>
 *
 * @author: kancy
 * @date: 2019/10/26 14:09
 **/
public class RsaAlgorithAction extends AbstractAlgorithmAction {
    /**
     * 检查数据
     *
     * @param data
     */
    @Override
    protected void checkAlgorithmData(AlgorithmData data) {
        super.checkAlgorithmData(data);
    }

    /**
     * 解密逻辑
     *
     * @param data
     */
    @Override
    protected String decrypt(AlgorithmData data) {
        if(CommonUtil.isEmpty(data.getSalt())){
            throw new AlertException("请输入RSA公钥！");
        }
        try {
            byte[] bytes = RSAUtil.decryptByPublicKey(data.getCipherText().trim().getBytes(), data.getSalt());
            return new String(bytes);
        } catch (Exception e) {
            throw new AlertException("RSA解密失败！");
        }
    }

    /**
     * 加密逻辑
     *
     * @param data
     */
    @Override
    protected String encrypt(AlgorithmData data) {
        if(CommonUtil.isEmpty(data.getPassword())){
            throw new AlertException("请输入RSA私钥！");
        }
        try {
            byte[] bytes = RSAUtil.encryptByPrivateKey(data.getPlainText().trim().getBytes(), data.getPassword());
            return new String(bytes);
        } catch (Exception e) {
            throw new AlertException("RSA加密失败！");
        }
    }

    @Override
    protected void update(RefreshObject object) {
        object.getPasswordObject().setVisible(true);
        object.getSaltObject().setVisible(true);
        object.getPasswordObject().setText(Constants.DEFAULT_RSA_PRIVATE_KEY);
        object.getSaltObject().setText(Constants.DEFAULT_RSA_PUBLIC_KEY);
        object.getLabel1Object().setVisible(true);
        object.getLabel1Object().setText("私钥:");
        object.getLabel2Object().setVisible(true);
        object.getLabel2Object().setText("公钥:");
    }

}
